
import { _decorator, Component, Node, Vec2, Vec3 } from 'cc';
import { CamreaCtrl } from '../game/CamreraCtrl';
import { Config } from '../utils/Config';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = BulletCtrl
 * DateTime = Thu Feb 29 2024 15:31:16 GMT+0800 (中国标准时间)
 * Author = heyongtao
 * FileBasename = BulletCtrl.ts
 * FileBasenameNoExtension = BulletCtrl
 * URL = db://assets/scripts/ai/BulletCtrl.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */
 
@ccclass('BulletCtrl')
export class BulletCtrl extends Component {
    // [1]
    // dummy = '';

    speed : number = 400;
    normalizedDirection : Vec2 = null;
    uniqueId : number = 0;
    //穿透
    penetrate : number = 1;
    //
    bulletNum : number = 1;
    setDestroy()
    {
        this.penetrate--;
    }

    setDirection(_dir : Vec2)
    {
        this.normalizedDirection = _dir;
    }

    setUniqueId(id : number)
    {
        this.uniqueId = id;
    }

    checkIsOutofBoundary()
    {
        let cameraPos = CamreaCtrl.GetInstance().getCameraPos();
        let aiPos = this.node.getPosition();
        if((cameraPos.x - Config.GetInstance().GameWinX/2 - Config.GetInstance().MapCornerRect) >= aiPos.x) return true;
        if((cameraPos.x + Config.GetInstance().GameWinX/2 + Config.GetInstance().MapCornerRect) <= aiPos.x) return true;
        if((cameraPos.y - Config.GetInstance().GameWinY/2) >= aiPos.y) return true;
        if((cameraPos.y + Config.GetInstance().GameWinY/2) <= aiPos.y) return true;
        return false;
    }

    start () {
        // [3]
    }

    update (deltaTime: number) {
        if(this.checkIsOutofBoundary() || !this.normalizedDirection || this.penetrate <= 0)
        {
            this.node.destroy();
            //console.log("bullet destory,id : ",this.uniqueId);
            return;
        }
        let curPos = this.node.getPosition();
        const moveDistance = this.speed * deltaTime;
        const scaledDirection = new Vec2(moveDistance*this.normalizedDirection.x,moveDistance*this.normalizedDirection.y);
        // vec2 add
        curPos.x += scaledDirection.x;
        curPos.y += scaledDirection.y;
        this.node.setPosition(curPos);
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
